<template>
  <div class="search-view" ref="search" @scroll.passive="searchScroll">
    <div class="top-nav">
      <div class="search-box">
        <div class="ipt-box">
          <div class="icon"><van-icon name="search" /></div>
          <input type="text" v-model="keywords" @keydown.enter="searchHandel" />
        </div>
        <div class="icon-cancle" @click="clearTheWords">
          <van-icon name="cross" />
        </div>
      </div>
      <div class="cancle" @click="goBack">取消</div>
    </div>
    <div class="content-box" v-if="contentData.length > 0">
      <div
        class="content-list-wrap"
        v-for="(item, index) in contentData"
        :key="item.id"
      >
        <VideoCom
          :allContentData="contentData"
          :scrollTop="scrollTop"
          :contentData="item"
          :isAutoplay="index == 0 ? true : item.isAutoplay"
          :loading="loading"
          :isFollow="item.isFollow"
          :isDislike="item.isDislike"
          :isLike="item.isLike"
          :index="index"
          @getVideoHeight="getTotalHeight($event)"
          @getFollowState="getFollowState(item)"
          @getLikeState="getLikeState(item)"
          @getDislikeState="getDislikeState(item)"
          @addShareCount="addShareCount(item)"
          @deleteData="deleteData(item)"
          @goTocomment="goTocomment(item)"
        />
      </div>
    </div>
    <div class="go-back-to-top" @click="goToTop" v-if="goToTopIconState">
      <van-icon name="arrow-up" /><br />返回<br />顶部
    </div>
    <h1 v-if="contentData.length == 0">搜索无结果，换个关键词吧!</h1>
  </div>
</template>

<script>
import { getSearchContent } from "@/api/home";
import VideoCom from "@/components/HomeCom/VideoCom.vue";
import { throttle } from "@/utils/throttle";
import {heightLight} from "@/utils/highLightWord"

export default {
  components: { VideoCom },
  name: "SearchView",
  data() {
    return {
      //搜索关键词
      keywords: null,
      //全部数据
      contentAllData: [],
      //展示数据
      contentData: [],
      //总高度
      totalHeight: 0,
      //加载状态
      loading: true,
      //滚动距离
      scrollTop: 0,
      //定时器
      timer: null,
      //返回顶部的按钮显示状态
      goToTopIconState: false,
      //截取的下标
      index1: 0,
      index2: 9,
    };
  },
  activated() {
    this.keywords = this.$route.params.keywords;
    this.getSearchContentData();
  },
  watch: {
    scrollTop(newval) {
      if (this.contentData.length == this.contentAllData.length) {
        this.loading = false;
      }
      if (newval + 500 > this.totalHeight && newval < this.totalHeight) {
        if (this.loading) {
          this.index1 += 10;
          this.index2 += 10;
          this.getData();
        }
      }
      if (newval >= this.totalHeight && !this.loading) {
        this.$toast({
          message: "没有更多啦~",
          position: "bottom",
        });
      }
    },
    loading(newval) {
      if (newval == false) {
        this.totalHeight = 0;
      }
    },
    "contentData.length"() {
      this.timer = setTimeout(() => {
        this.getTotalHeight();
        this.timer = null;
      }, 100);
    },
  },
  methods: {
    //返回上一级路由
    goBack() {
      this.$router.go(-1);
    },
    //获取搜索数据
    getSearchContentData() {
      this.contentData = [];
      this.index1 = 0;
      this.index2 = 9;
      getSearchContent({ axios: this.$axios }).then((data) => {
        //  this.contentData=[...data.data];
        let res = data.data.filter((item) => {
          if (item.content.indexOf(this.keywords) != -1) {
            item.content=heightLight(item.content,item.content[item.content.indexOf(this.keywords)])
          }
          return item.content.indexOf(this.keywords) != -1;
        });
        // console.log(res);
        this.contentAllData = res;
        for (let i = this.index1; i <= this.index2; i++) {
          if (i == this.contentAllData.length) {
            break;
          }
          this.contentData.push(this.contentAllData[i]);
        }
        // console.log(this.contentData);
      });
      //定时器延迟拿取数据
      this.timer = setTimeout(() => {
        this.getFollowedData();
        this.timer = null;
      }, 100);
    },
    //获取截取的数据实现懒加载
    getData() {
      for (let i = this.index1; i <= this.index2; i++) {
        if (i == this.contentAllData.length) {
          break;
        }
        this.contentData.push(this.contentAllData[i]);
      }
    },
    //滚动
    searchScroll: throttle(function () {
      this.scrollTop = this.$refs.search.scrollTop;
      if (this.scrollTop >= 150) {
        this.goToTopIconState = true;
      } else {
        this.goToTopIconState = false;
      }
    }, 500),
    //返回顶部方法
    goToTop() {
      this.$refs.search.scrollTo(0, 0);
    },
    //获取所有内容的高度
    getTotalHeight(val) {
      if (val != undefined) {
        this.totalHeight += val;
      }
    },
    //关注
    getFollowState(item) {
      item.isFollow = !item.isFollow;
      let followedData = JSON.parse(
        window.localStorage.getItem("followedData")
      );
      let idArr = [];
      followedData.forEach((item) => {
        idArr.push(item.id);
      });
      if (item.isFollow && idArr.indexOf(item.user.id) == -1) {
        followedData.push(item.user);
        window.localStorage.setItem(
          "followedData",
          JSON.stringify(followedData)
        );
      } else {
        // console.log(followedData.indexOf(item.user));
        followedData.forEach((item2, index) => {
          if (item2.id == item.user.id) {
            followedData.splice(index, 1);
            window.localStorage.setItem(
              "followedData",
              JSON.stringify(followedData)
            );
          }
        });
      }
    },
    //点赞
    getLikeState(item) {
      item.isLike = !item.isLike;
      if (item.isLike) {
        item.isDislike = false;
        item.votes.up++;
      } else {
        item.votes.up--;
      }
    },
    //踩
    getDislikeState(item) {
      item.isDislike = !item.isDislike;
      if (item.isDislike && item.isLike) {
        item.isLike = false;
        item.votes.up--;
      }
    },
    //分享
    addShareCount(item) {
      item.share_count++;
    },
    //删除
    deleteData(item) {
      this.$dialog
        .confirm({
          title: "确定要删除吗?",
        })
        .then(() => {
          // on confirm
          this.contentData.forEach((item2, index) => {
            if (item2 == item) {
              this.contentData.splice(index, 1);
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    //获取已关注
    getFollowedData() {
      let followedData = JSON.parse(
        window.localStorage.getItem("followedData")
      );
      let followedDataId = [];
      followedData.forEach((item) => {
        followedDataId.push(item.id);
      });
      this.contentData.forEach((item) => {
        if (followedDataId.indexOf(item.user.id) != -1) {
          item.isFollow = true;
        } else {
          item.isFollow = false;
        }
      });
    },
    //跳转评论详情页
    goTocomment(item) {
      window.localStorage.setItem("commentContentData", JSON.stringify(item));
      let dataId = item.id;
      if (dataId != 125654473 && dataId != 125657703) {
        dataId = 125654473;
      }
      this.$router.push(`/comment?id=${dataId}`);
    },
    //搜索方法
    searchHandel() {
      if (
        this.keywords != "" &&
        this.keywords.length > 0 &&
        this.keywords != this.$route.params.keywords
      ) {
        this.$router.replace({
          name: "SearchView",
          params: {
            keywords: this.keywords,
          },
        });
        this.keywords = this.$route.params.keywords;
        this.getSearchContentData();
      }
    },
    //清除搜索词
    clearTheWords() {
      this.keywords = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.search-view {
  width: 100vw;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  .top-nav {
    width: 100%;
    height: 50px;
    box-sizing: border-box;
    border-bottom: 1px solid #ddd;
    display: flex;
    align-items: center;
    position: fixed;
    left: 10px;
    top: 0px;
    background-color: #fff;
    z-index: 100;
    .search-box {
      width: 300px;
      height: 35px;
      background-color: rgb(240, 240, 240);
      border-radius: 8px;
      display: flex;
      justify-content: space-between;
      padding: 0 10px;
      align-items: center;
      box-sizing: border-box;
      margin-right: 10px;
      .ipt-box {
        display: flex;
        .icon {
          color: #666;
          font-size: 16px;
          margin-right: 5px;
        }
        input {
          background-color: rgb(240, 240, 240);
        }
      }
      .icon-cancle {
        width: 20px;
        height: 20px;
        background-color: #ccc;
        border-radius: 999px;
        color: #fff;
        text-align: center;
        line-height: 20px;
      }
    }
    .cancle {
      font-weight: 600;
      font-size: 16px;
    }
  }
  .content-box {
    width: 100%;
    padding: 50px 0;
  }
  h1 {
    text-align: center;
    font-size: 25px;
    font-weight: 600;
    margin-top: 40%;
  }
  .go-back-to-top {
    width: 70px;
    height: 70px;
    font-size: 20px;
    background-color: rgb(255, 223, 51);
    text-align: center;
    line-height: 21px;
    border-radius: 999px;
    position: fixed;
    right: -7px;
    bottom: 90px;
    transform: scale(0.5);
    z-index: 99;
  }
}
</style>